package org.blog.inteceptor;

import com.alibaba.fastjson.JSONObject;
import org.blog.common.ResultVO;
import org.blog.exception.BaseErrorEnum;
import org.blog.exception.BaseException;
import org.blog.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token 拦截器
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private RedisUtils redisUtils;

    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //跨域请求会首先发一个option请求，直接返回正常状态并通过拦截器
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
        //token 放在请求header的Authorization 中
        String token = request.getHeader("Authorization");
        if (token != null) {
//            boolean result= TokenUtils.verify(token);  TODO:需要删除
            if (redisUtils.getString("token").equals(token)) {
                return true;
            } else {
                throw new BaseException(BaseErrorEnum.USER_INVALID);
            }
        }

        response.setContentType("application/json; charset=utf-8");
        try {
            ResultVO result = new ResultVO("500", "Token verify fail!", null);
            JSONObject json = (JSONObject) JSONObject.toJSON(result);
            response.getWriter().append(json.toString());
            log.info("认证失败，未通过拦截器");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        /**
         * 还可以在此处检验用户存不存在等操作
         */
        return false;
    }
}